package communication.server.vertx.service.impl;

import communication.common.business.base.FcrSocketAddress;
import communication.common.business.hole.P2pHoleRequest;
import communication.common.business.hole.ServerNetService;
import communication.common.vertx.net.NetManager;
import communication.server.vertx.dao.DeviceInfoDao;
import communication.server.vertx.entity.DeviceInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/** netService的实现类
 * @author mac
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ServerNetServiceImpl implements ServerNetService {

    private final DeviceInfoDao deviceInfoDao;

    private final NetManager netManager;

    /**
     *
     *  todo:
     * 转发打洞请求。
     *  1. 根据 targetUserId 获取该用户的设备信息；
     *  2. 根据设备信息获取socket地址信息
     *  3. 向目标设备的socket地址转发打洞请求
     *
     *
     * @param request 要转发的请求
     * @return
     */
    @Override
    public void hole(P2pHoleRequest request , FcrSocketAddress remoteSocketAddress) throws Exception {
        log.info("接收到打洞转发请求, request:{} ,remoteSocketAddress:{} ",request,remoteSocketAddress);
        if(StringUtils.isEmpty(request.getSourceDevice())){
            request.setSourceDevice(remoteSocketAddress.getAddress());
        }


        // 1. 获取设备信息
        DeviceInfo deviceInfo = deviceInfoDao.getByUserId(request.getTargetUserId());
        if(deviceInfo==null){
            throw new Exception("用户设备不存在！");
        }

        if(!deviceInfo.isOnlineFlg()){
            throw new Exception("用户设备不在线！");
        }

        // 2. 获取socket地址信息
        String netAddress = deviceInfo.getNetAddress();
        String[] socketAddres=netAddress.split(":");

        // todo:
//        NetSocketUtil.sendObj(netManager.getDatagramSocket(), socketAddres[0], Integer.parseInt(socketAddres[1]), MsgDataUtil.createHoleRequest(request))
//        .future()
//        .onSuccess(a->log.info("hole请求转发完成"));
    }
}
